﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;

namespace ImageWater
{
    public class ImageWaterHandler
    {
        /// <summary>
        /// 图片加水印文字
        /// </summary>
        /// <param name="filePath">旧图片地址</param>
        /// <param name="text">水印文字</param>
        /// <param name="savePath">新图片地址</param>
        /// <param name="Alpha">透明度</param>
        /// <param name="fontSize">字体大小</param>
        public static void AddWaterText(string filePath, string text, string savePath, double Alpha, int fontSize)
        {
            using (System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(filePath))
            {
                int imgPhotoWidth = imgPhoto.Width;
                int imgPhotoHeight = imgPhoto.Height;
                using (Bitmap bmPhoto = new Bitmap(imgPhotoWidth, imgPhotoHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
                {
                    bmPhoto.SetResolution(72, 72);
                    using (Graphics gbmPhoto = Graphics.FromImage(bmPhoto))
                    {
                        //gif背景色
                        gbmPhoto.Clear(Color.FromName("white"));
                        gbmPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                        gbmPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        gbmPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, imgPhotoWidth, imgPhotoHeight), 0, 0, imgPhotoWidth, imgPhotoHeight, GraphicsUnit.Pixel);
                        System.Drawing.SizeF crSize = new SizeF();
                        System.Drawing.Font font = new Font("宋体", fontSize, FontStyle.Bold);
                        
                        //测量指定区域
                        crSize = gbmPhoto.MeasureString(text, font);
                        float y = imgPhotoHeight - crSize.Height;
                        float x = imgPhotoWidth - crSize.Width;
                        System.Drawing.StringFormat StrFormat = new System.Drawing.StringFormat();
                        StrFormat.Alignment = System.Drawing.StringAlignment.Center;

                        //画两次制造透明效果
                        System.Drawing.SolidBrush semiTransBrush2 = new System.Drawing.SolidBrush(Color.FromArgb(Convert.ToInt32(Alpha*255), 56, 56, 56));
                        gbmPhoto.DrawString(text, font, semiTransBrush2, x + 1, y + 1);

                        System.Drawing.SolidBrush semiTransBrush = new System.Drawing.SolidBrush(Color.FromArgb(Convert.ToInt32(Alpha * 255), 176, 176, 176));
                        gbmPhoto.DrawString(text, font, semiTransBrush, x, y);
                        bmPhoto.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);
                    }
                }
            }
        }
    }
}
